<script setup>
import { ref } from 'vue'
import api from '@/api'
import { parsePage, parseQuery } from '@/utils'
import { useRoute, useRouter } from 'vue-router'
import { Modal } from '@arco-design/web-vue'
import uploadImage from '@/components/uploadImage.vue'

const $route = useRoute()
const $router = useRouter()

// const listFormData = ref({
//   page: parsePage($route.query.page, 1),
//   keyword: $route.query.keyword || '',
// })
const keyword = ref('')
const pageVal = ref(1)
const pageSize = ref(10)
const listData = ref([])
const listTotal = ref(0)
const listLoading = ref(false)

const getListData = async (page = 1) => {
  listLoading.value = true
  try {
    // listFormData.value.page = page
    // const query = parseQuery(listFormData.value)
    // $router.replace({ query })
    const res = await api.get('ip/materials/categories', {
      params: {
        keyword: keyword.value,
        page,
        pageSize: pageSize.value,
      },
    })
    listData.value = res.data.data
    listTotal.value = res.data.total
    pageVal.value = page
  } catch (error) {
    console.error(error)
  }
  listLoading.value = false
}

const resetListData = () => {
  // listFormData.value.keyword = ''
  keyword.value = ''
  getListData()
}

getListData()

const formRef = ref()
const formItem = ref()
const formLoading = ref(false)
const formVisible = ref(false)
const formData = ref({
  name: '',
  image: '',
})
const formRules = {
  name: [
    {
      required: true,
      message: '请填写分类名称',
    },
  ],
  image: [
    {
      required: true,
      message: '请上传分类图片',
    },
  ],
}

const create = () => {
  formRef.value?.resetFields()
  formVisible.value = true
}

const update = (item) => {
  formRef.value?.resetFields()
  formItem.value = item
  formData.value.name = item.name
  formData.value.image = item.image
  formVisible.value = true
}

const formSubmit = async () => {
  if (await formRef.value.validate()) {
    return false
  }

  formLoading.value = true

  try {
    if (formItem.value) {
      await api.put(
        'ip/materials/categories/' + formItem.value.id,
        formData.value
      )
    } else {
      await api.post('ip/materials/categories', formData.value)
    }
    formRef.value?.resetFields()
    formVisible.value = false
    getListData()
  } catch (error) {
    console.error(error)
  }

  formLoading.value = false

  return false
}

const del = (item) => {
  Modal.confirm({
    title: '删除分类',
    content: '您确定要删除吗？',
    bodyStyle: 'text-align:center',
    onBeforeOk: async () => {
      await api.delete('ip/materials/categories/' + item.id)

      getListData()
    },
  })
}
</script>

<template>
  <div class="page">
    <div class="header">
      <a-form class="page-form"
              layout="inline"
              @submit="getListData()">
        <a-space>
          <a-input v-model.trim="keyword"
                   placeholder="分类名称"
                   allow-clear />

          <a-button type="primary"
                    html-type="submit">
            <!-- <template #icon>
              <icon-search />
            </template> -->
            查询
          </a-button>

          <!-- <a-button @click="resetListData">
            <template #icon>
              <icon-refresh />
            </template>重置
          </a-button> -->
        </a-space>
      </a-form>

      <a-space>
        <a-button type="primary"
                  @click="create">添加分类</a-button>
      </a-space>
    </div>

    <a-table :data="listData"
             @page-change="getListData"
             :pagination="{
              showTotal: true,
              size: 'small',
              total: listTotal,
              pageSize: pageSize,
              current: pageVal,
            }">
      <template #columns>
        <a-table-column title="序号"
                        :width="60">
          <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
        </a-table-column>
        <a-table-column title="分类图标"
                        :width="200">
          <template #cell="{ record }">
            <a-image width="100"
                     height="100"
                     fit="cover"
                     :src="record.image" />
          </template>
        </a-table-column>
        <a-table-column title="分类名称"
                        data-index="name"></a-table-column>
        <a-table-column align="right"
                        :width="88">
          <template #cell="{ record }">
            <a-space>
              <a-button type="primary"
                        size="mini"
                        @click="update(record)">编辑</a-button>
              <a-button type="primary"
                        status="danger"
                        size="mini"
                        @click="del(record)">
                删除
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <a-modal v-model:visible="formVisible"
             :title="(formItem ? '编辑' : '添加') + '分类'"
             width="600px"
             :ok-loading="formLoading"
             :on-before-ok="formSubmit">
      <a-form ref="formRef"
              :model="formData"
              :rules="formRules">
        <a-form-item field="image"
                     label="分类图标"
                     help="请上传jpg、png、gif格式图片、文件大小不能超过1MB"
                     validate-trigger="input"
                     style="margin-bottom: 10px">
          <uploadImage v-model="formData.image"
                       width="200px"
                       height="200px"></uploadImage>
        </a-form-item>
        <a-form-item field="name"
                     label="分类名称">
          <a-input :style="{width:'400px'}"
                   v-model="formData.name"
                   placeholder="请输入分类名称"
                   allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.page {
  height: 100%;
}

.header {
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.page .header .page-form {
  justify-content: flex-start !important;
}
</style>
